import { useState } from 'react';

interface RatingComponentProps {
  averageRating?: number | null;
  ratingCount?: number;
  userRating?: number | null;
  onRatingChange?: (rating: number) => void;
  readOnly?: boolean;
}

export default function RatingComponent({
  averageRating = 0,
  ratingCount = 0,
  userRating = null,
  onRatingChange,
  readOnly = false
}: RatingComponentProps) {
  const [hoverRating, setHoverRating] = useState(0);
  const [selectedRating, setSelectedRating] = useState(userRating || 0);
  
  const handleRatingClick = (rating: number) => {
    if (!readOnly && onRatingChange) {
      setSelectedRating(rating);
      onRatingChange(rating);
    }
  };
  
  const displayRating = hoverRating || selectedRating || 0;
  
  return (
    <div className="flex flex-col space-y-2">
      {/* 平均评分显示 */}
      {averageRating > 0 && (
        <div className="flex items-center space-x-2">
          <span className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
            平均评分: {averageRating.toFixed(1)}
          </span>
          <span className="text-xs text-zinc-500 dark:text-zinc-400">
            ({ratingCount} 人评分)
          </span>
        </div>
      )}
      
      {/* 评分星星 */}
      <div className="flex items-center space-x-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type="button"
            onClick={() => handleRatingClick(star)}
            onMouseEnter={() => !readOnly && setHoverRating(star)}
            onMouseLeave={() => !readOnly && setHoverRating(0)}
            disabled={readOnly}
            className={`p-1 rounded-full transition-colors ${!readOnly ? 'cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800' : ''}`}
            aria-label={`${star} 星`}
          >
            <svg 
              xmlns="http://www.w3.org/2000/svg" 
              width="24" 
              height="24" 
              viewBox="0 0 24 24" 
              fill={star <= displayRating ? "currentColor" : "none"} 
              stroke="currentColor" 
              strokeWidth="2" 
              strokeLinecap="round" 
              strokeLinejoin="round"
              className={star <= displayRating ? 'text-yellow-400' : 'text-zinc-300 dark:text-zinc-600'}
            >
              <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
            </svg>
          </button>
        ))}
        {!readOnly && selectedRating > 0 && (
          <span className="ml-2 text-sm text-zinc-600 dark:text-zinc-400">
            您的评分: {selectedRating} 星
          </span>
        )}
      </div>
    </div>
  );
}